#!/usr/bin/bash
set -e

source ./promtail.properties

# 获取当前主机ip地址
HOST_IP=$(/usr/sbin/ip addr | awk '/^[0-9]+: / {}; /inet.*global/ {print gensub(/(.*)\/(.*)/, "\\1", "g", $2)}' |grep -e $(hostname -i|awk  '{print $1}') -e ${ZCM_SERVER_VIP: 0: 5}|head -1)

# 开始
function main() {
echo deploy init

# 判断目录是否存在
if [ ! -d /etc/promtail/  ];then
  sudo mkdir  /etc/promtail
  sudo chmod a+w /etc/promtail/
  sudo cp ./config.yaml /etc/promtail/
  sudo cp ./target.yaml /etc/promtail/
  sudo chmod a+w /etc/promtail/config.yaml /etc/promtail/target.yaml
fi

if [ -z $HOST_IP ];then
  echo the host_ip is empty,please check the promtail.properties file
  exit 1
fi
sudo touch /var/log/promtail-positions.yaml
sudo chmod 775 /var/log/promtail-positions.yaml
# 定制化配置文件
sudo sed -i s/HOST_IP/$HOST_IP/g /etc/promtail/config.yaml
sudo sed -i s#TIME_ZONE#$TIME_ZONE#g /etc/promtail/config.yaml
sudo sed -i s/ZCM_SERVER_VIP/$ZCM_SERVER_VIP/g /etc/promtail/config.yaml
sudo sed -i s/HTTP_LISTEN_PORT/$HTTP_LISTEN_PORT/g /etc/promtail/config.yaml

service
}

# service化
function service() {
sudo tar -zxf ./promtail-2.4.0linux-amd64.tar.gz

sudo chmod 0755 promtail-2.4.0linux-amd64
# 先停止,可重复部署
if [ -f /usr/lib/systemd/system/promtail.service ];then
sudo systemctl stop promtail
fi

sudo cp promtail-2.4.0linux-amd64 /usr/sbin/promtail
sudo touch /usr/lib/systemd/system/promtail.service
sudo chmod o+w /usr/lib/systemd/system/promtail.service
sudo chmod a+x /usr/sbin/promtail
sudo cat << EOF > /usr/lib/systemd/system/promtail.service
[Service]
Type=simple
User=$USER
ExecStart=/usr/sbin/promtail -config.file=/etc/promtail/config.yaml
Restart=on-failure

[Install]
WantedBy=multi-user.target

[Unit]
Description=mtail service daemon
After=network.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable promtail
sudo systemctl start promtail
echo sudo systemctl status promtail
sudo systemctl status promtail
echo deploy end
}


main
